package com.hk.commons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestParam;

import com.hk.commons.entity.pay.FM;
import com.hk.commons.utils.sys.MD5Crypter;

public class GetBankInfoUtil {
	
	private static Logger logger = LoggerFactory.getLogger(GetBankInfoUtil.class);

	
	@Value("${fy.Secret}")
	private static String fySecret;

	@Value("${fy.mchntCd}")
	private static String fyMchntCd;

	@Value("${fy.scheme}")
	private static String scheme;

	@Value("${fy.valiFour}")
	private static String realUrl;

	@Value("${fy.validateCardPath}")
	private static String path;

	@Value("${fy.getBankPath}")
	private static String getBankpath;

	// @ResponseBody
	// @RequestMapping(value = "/getBankCardInfo", method = RequestMethod.GET)
	public static FM getBankCardInfo(@RequestParam String cardNum) {
		URIBuilder builder = new URIBuilder().setScheme(scheme)
				.setHost(realUrl).setPath(getBankpath);
		Map<String, String> trimmedParams = new HashMap<>();
		String MchntCd = fyMchntCd;
		String Ono = cardNum;
		String allUrl = MchntCd + "|" + Ono + "|" + fySecret;
		String Sign = MD5Crypter.md5Encrypt(allUrl);
		String fm = "<FM><MchntCd>" + MchntCd + "</MchntCd>" + "<Ono>" + Ono
				+ "</Ono>" + "<Sign>" + Sign + "</Sign></FM> ";
		trimmedParams.put("FM", fm);
		CloseableHttpResponse resp = null;
		CloseableHttpClient httpClient = null;
		try {
			URI uri = builder.build();
			RequestBuilder requestBuilder = RequestBuilder.post(uri);
			List<NameValuePair> kvs = new ArrayList<>();
			for (String key : trimmedParams.keySet()) {
				kvs.add(new BasicNameValuePair(key, trimmedParams.get(key)));
			}
			requestBuilder.setEntity(new UrlEncodedFormEntity(kvs, "UTF-8"));
			HttpUriRequest request = requestBuilder.build();

			httpClient = HttpClients.custom().setMaxConnPerRoute(200).build();

			resp = httpClient.execute(request);

			if (resp.getStatusLine().getStatusCode() >= 300) {
				System.err.println("Something wrong: "
						+ resp.getStatusLine().toString());
			}
			BufferedReader input = new BufferedReader(new InputStreamReader(
					resp.getEntity().getContent(), "UTF-8"));
			StringBuilder sb = new StringBuilder();
			char[] buf = new char[1000];
			int count;
			while ((count = input.read(buf)) > 0) {
				sb.append(buf, 0, count);
			}
			
			logger.info("查询该银行卡号信息如下：Ono={},sb={}", Ono, sb.toString());
			// System.out.println(sb.toString());
			String result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
					+ sb.toString().toLowerCase();
			BeanAndXMLTurn<FM> ff = new BeanAndXMLTurn<FM>();
			FM fmresultFm = ff.XMLStringToBean(result, new FM());

			return fmresultFm;
		} catch (IOException | URISyntaxException e) {
			logger.error("fyValidate()方法异常！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (resp != null) {
					resp.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				logger.error("获取卡信息异常");
				e.printStackTrace();

			}
		}
	}

}
